<template>
  <view class="comment-container">
    <!-- 空状态提示 -->
    <view v-if="comments.length === 0" class="no-comments">
      暂无评论，快来发表你的评论
    </view>
    <!-- 评论列表 -->
    <view v-else v-for="(comment, index) in comments" :key="index" class="comment-item">
      <!-- 头像 + 昵称 -->
      <view class="comment-header">
        <u-avatar :src="comment.avatar" size="40" @click="navigateToUserProfile(comment.userId)"></u-avatar>
        <text class="username">{{ comment.nickname }}</text>
      </view>
      <!-- 评论内容 -->
      <view class="comment-content">
        <text class="content">{{ comment.content }}</text>
        <view class="meta-like">
          <view class="meta">
            <text class="date">{{ formatDate(comment.createTime) }}</text>
            <text class="reply" @click="handleReply(comment)">· 回复</text>
          </view>
          <view class="like">
            <u-icon name="thumb-up" size="20"></u-icon>
            <text>{{ comment.likes }}</text>
          </view>
        </view>
      </view>
      <!-- 子评论列表 -->
      <view v-if="comment.replies && comment.replies.length > 0" class="sub-comments">
        <view v-for="(reply, replyIndex) in comment.replies" :key="replyIndex" class="comment-item">
          <view class="comment-header">
            <u-avatar :src="reply.avatar" size="40" @click="navigateToUserProfile(reply.userId)"></u-avatar>
            <text class="username">{{ reply.nickname }}</text>
          </view>
          <view class="comment-content">
            <text class="content">{{ reply.content }}</text>
            <view class="meta-like">
              <view class="meta">
                <text class="date">{{ formatDate(reply.createTime) }}</text>
                <text class="reply" @click="handleReply(reply)">· 回复</text>
              </view>
              <view class="like">
                <u-icon name="thumb-up" size="20"></u-icon>
                <text>{{ reply.likes }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, defineProps, defineEmits } from 'vue';
import { getCommentsByArticleId } from '@/apis/homeAPI';

// 接收文章ID和刷新键
const props = defineProps({
  articleId: {
    type: Number,
    default: 1,
    required: false
  },
  refreshKey: { // 用于触发刷新的键
    type: Number,
    default: 0
  }
});

// 触发回复事件
const emit = defineEmits(['reply-comment']);

// 评论列表数据
const comments = ref([]);

// 获取评论列表
const fetchComments = async () => {
  try {
    const response = await getCommentsByArticleId(props.articleId);
    console.log('获取评论成功:', response.data);
    if (response.data.code === 200) {
      // 重新创建数组，强制触发响应式更新
      comments.value = [...response.data.data];
    }
  } catch (error) {
    console.error('获取评论失败:', error);
  }
};

// 监听refreshKey变化，自动触发刷新
watch(
    () => props.refreshKey,
    (newVal) => {
      // 移除旧的 newVal !== oldVal 判断，只要有变化就刷新
      console.log('refreshKey 变化，触发刷新，当前值:', newVal);
      fetchComments(); // 强制调用刷新
    },
    { immediate: false } // 确保组件挂载后才监听
);

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 处理回复
const handleReply = (item) => {
  if (!item.id || !item.nickname) {
    console.error('回复数据不完整:', item);
    return;
  }
  emit('reply-comment', {
    id: item.id,
    username: item.nickname
  });
};
// 导航到用户详情页
const navigateToUserProfile = (userId) => {
  if (!userId) return;
  uni.navigateTo({ url: `/pages/profile/profile?userId=${userId}` });
};
// 组件挂载时加载评论
onMounted(() => {
  fetchComments();
});
</script>

<style scoped lang="scss">
.comment-container {
  padding: 10px;
  .comment-item {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
    .comment-header {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      .username {
        margin-left: 10px;
        font-size: 14px;
        font-weight: bold;
        color: #333;
      }
    }
    .comment-content {
      margin-left: 50px;
      .content {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
        display: block;
      }
      .meta-like {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #999;
        .meta {
          display: flex;
          gap: 10px;
          .reply {
            cursor: pointer;
            color: #666;
          }
        }
        .like {
          display: flex;
          align-items: center;
          margin-left: auto;
          gap: 5px;
        }
      }
    }
  }
  .sub-comments {
    padding-left: 20px;
    margin-top: 10px;
  }
  .no-comments {
    color: #999;
    text-align: center;
    padding: 20px 0;
  }
}
</style>